<template>
  <BasicModal
    v-if="formType === 'modal'"
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    @cancel="handleClose"
    :paddingRight="15"
    :bodyStyle="{ minHeight: '400px !important' }"
  >
    <SimpleForm ref="formRef" :formProps="formProps" :formModel="state.formModel" />
  </BasicModal>
  <BasicDrawer
    v-else
    showFooter
    v-bind="$attrs"
    @register="registerDrawer"
    :title="getTitle"
    @ok="handleSubmit"
    @cancel="handleClose"
  >
    <SimpleForm ref="formRef" :formProps="formProps" :formModel="state.formModel" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';
  import SimpleForm from '/@/components/SimpleForm/src/SimpleForm.vue';
  import { addFormExecute, getFormExecute, updateFormExecute } from '/@/api/form/execute';
  import { execute } from '/@/api/liteflow';
  import { apiConfigFunc } from '/@/utils/event/design';
  import { cloneDeep } from 'lodash-es';

  const emit = defineEmits(['success', 'register']);
  const { notification } = useMessage();
  const { filterFormSchemaAuth } = usePermission();
  const formRef = ref();

  const formProps = ref<any>({});
  const props = defineProps({
    formType: String,
    formWidth: Number,
  });
  let releaseId = ``;

  const state = reactive({
    formModel: {},
    isUpdate: true,
    isView: false,
    rowId: '',
    pkField: 'id',
    formEventConfig: [],
    key: 0,
  });

  const { t } = useI18n();

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    if (props.formType === 'modal') {
      handleInner(data, setModalProps);
    }
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    if (props.formType === 'drawer') {
      handleInner(data, setDrawerProps);
    }
  });

  const getTitle = computed(() =>
    state.isView ? t('查看') : !state.isUpdate ? t('新增') : t('编辑'),
  );

  async function handleInner(data, setPropsData) {
    formProps.value = data.formProps;
    state.formEventConfig = data.formEventConfig;
    state.isView = !!data?.isView;
    state.isUpdate = !!data?.isUpdate;
    state.pkField = data.pkField;
    releaseId = data.releaseId;
    formProps.value.schemas = filterFormSchemaAuth(formProps.value.schemas!);

    const viewformProps = cloneDeep(data.formProps);
    setDisabled(viewformProps.schemas);

    formRef.value.setProps(state.isView ? viewformProps : data.formProps);

    await formRef.value.setDefaultValue();

    //初始化表单
    executeFormEvent(state.formEventConfig[0]);
    //加载表单
    executeFormEvent(state.formEventConfig[2]);

    if (state.isUpdate || state.isView) {
      state.rowId = data.id;
      const record = await getFormExecute({ releaseId, id: state.rowId });
      formRef.value.setFieldsValue(record);
      //获取表单数据
      executeFormEvent(state.formEventConfig[1]);
    } else {
      formRef.value.resetFields();
    }

    setPropsData({
      destroyOnClose: true,
      maskClosable: false,
      showCancelBtn: !state.isView,
      showOkBtn: !state.isView,
      canFullscreen: true,
      width: props.formWidth,
    });
  }

  function setDisabled(schemas) {
    const layoutComponents = ['tab', 'grid', 'card'];
    schemas?.map((info) => {
      if (layoutComponents.includes(info.type!)) {
        info.children?.map((childInfo) => {
          childInfo.list.map((com) => {
            if (layoutComponents.includes(com.type)) {
              setDisabled(childInfo.list);
            } else {
              com.dynamicDisabled = true;
            }
          });
        });
      } else if (info.type == 'one-for-one') {
        setDisabled(info.componentProps.childSchemas);
      } else {
        info.dynamicDisabled = true;
      }
    });
  }

  //执行表单事件
  function executeFormEvent(formEventConfig) {
    if (!formEventConfig.length) return;
    formEventConfig.map((x) => {
      x.nodeInfo?.processEvent?.map(async (config) => {
        if (config.operateType === 'api') {
          await apiConfigFunc(config.operateConfig, true, state.formModel);
        } else if (config.operateType === 'liteflow') {
          await execute(config.operateConfig, state.formModel);
        }
      });
    });
  }

  async function handleSubmit() {
    try {
      const values = await formRef.value?.validate();
      //添加隐藏组件
      if (formProps.value.hiddenComponent?.length) {
        formProps.value.hiddenComponent.forEach((component) => {
          values[component.bindField] = component.value;
        });
      }
      props.formType === 'modal'
        ? setModalProps({ confirmLoading: true })
        : setDrawerProps({ confirmLoading: false });

      // TODO custom api
      if (!state.isUpdate) {
        //false 新增
        await addFormExecute({ releaseId, formData: values });

        notification.success({
          message: t('提示'),
          description: t('新增成功！'),
        }); //提示消息
      } else {
        values[state.pkField] = state.rowId;
        await updateFormExecute({ releaseId, formData: values });

        notification.success({
          message: t('提示'),
          description: t('修改成功！'),
        }); //提示消息
      }

      //提交表单事件
      executeFormEvent(state.formEventConfig[3]);
      props.formType === 'modal' ? closeModal() : closeDrawer();
      formRef.value.resetFields();
      emit('success');
    } catch (error) {
    } finally {
      props.formType === 'modal'
        ? setModalProps({ confirmLoading: false })
        : setDrawerProps({ confirmLoading: false });
    }
  }

  function handleClose() {
    formRef.value.resetFields();
  }
</script>
